/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.theme.passport.controller.app;


import com.theme.common.base.StringHandler;
import com.theme.common.frame.exception.ErrorCode;
import com.theme.common.mvc.utils.RedisKeys;
import com.theme.common.mvc.validator.ValidatorUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.entity.UserEntity;
import com.theme.passport.entity.constant.UserOriginEnum;
import com.theme.passport.entity.constant.UserReviewStatusEnum;
import com.theme.passport.form.ForgetPasswordForm;
import com.theme.passport.form.RegisterForm;
import com.theme.passport.form.RegisterMoblieForm;
import com.theme.passport.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 注册
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP注册接口-[账号和密码]")
public class AppRegisterController {

    @Autowired
    private UserService userService;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> redisCache;

    @Value("${user.default-avatar}")
    private String defaultAvatar ;

    @Value("${sms.aliyun.code}")
    private String smsAliyunCode ;

    @PostMapping("register")
    @ApiOperation("用户名密码注册")
    public R register(@RequestBody RegisterForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);

        //校验用户是否存在
        UserEntity user = userService.queryByMobile(form.getMobile());
        if (user != null){
            return R.error(ErrorCode.REGISTER_USER_PHONE_EXIST.getCode(),ErrorCode.REGISTER_USER_PHONE_EXIST.getMsg());
        }

        user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getMobile());
        user.setAvatar(defaultAvatar);
        user.setNickname(form.getNickname());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setOrigin(UserOriginEnum.APP.getValue());
        user.setReviewStatus(UserReviewStatusEnum.AUDIT_PASS.getValue());
        user.setCreateTime(new Date());
        userService.save(user);
        return R.ok();
    }

    @PostMapping("moblie/register")
    @ApiOperation("手机号验证码注册")
    public R moblieRegister(@RequestBody RegisterMoblieForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);

        //校验验证码是否合适
        R r = validatorCode(form.getMobile(),form.getCode());
        if (!R.isOk(r)){
            return r;
        }

        //校验用户是否存在
        UserEntity user = userService.queryByMobile(form.getMobile());
        if (user != null){
            return R.error(ErrorCode.REGISTER_USER_PHONE_EXIST.getCode(),ErrorCode.REGISTER_USER_PHONE_EXIST.getMsg());
        }

        user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getMobile());
        user.setAvatar(defaultAvatar);
        user.setNickname(form.getNickname());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setOrigin(UserOriginEnum.APP.getValue());
        user.setReviewStatus(UserReviewStatusEnum.AUDIT_PASS.getValue());
        user.setCreateTime(new Date());
        userService.save(user);
        return R.ok();
    }

    @PostMapping("forgetPassword")
    @ApiOperation("忘记密码")
    public R forgetPassword(@RequestBody ForgetPasswordForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);

        //校验验证码是否合适
        R r = validatorCode(form.getMobile(),form.getCode());
        if (!R.isOk(r)){
            return r;
        }

        //校验用户是否存在
        UserEntity user = userService.queryByMobile(form.getMobile());
        if (user == null){
            return R.error(ErrorCode.FORM_USER_USERNAME_ERROR.getCode(),ErrorCode.FORM_USER_USERNAME_ERROR.getMsg());
        }

        user.setMobile(form.getMobile());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        userService.updateUserById(user);
        return R.ok();
    }

    private R validatorCode(String mobile, String code) {

        String loginKey = RedisKeys.SEND_CODE.concat(mobile);
        String result = redisCache.get(loginKey);
        if (StringHandler.isEmpty(result)){
            return R.error(ErrorCode.FORM_USER_CODE_ERROR.getCode(),"验证码已过期");
        }
        if (result.equals(code)){
            return R.ok();
        }
        return R.error(ErrorCode.FORM_USER_CODE_ERROR.getCode(),ErrorCode.FORM_USER_CODE_ERROR.getMsg());

    }

}
